#include "XStormBase.h"

namespace Xts
{
	namespace IceRuntime
	{
		XStormBase::XStormBase(const Ice::CommunicatorPtr& pIc, const Ice::LoggerPtr& pLogger)
			:x_pIc(pIc), x_pLogger(pLogger), x_topicManagerPrx(NULL)
		{
		}

		XStormBase::~XStormBase(void)
		{
		}

		bool XStormBase::IsTopicManagerValid()
		{
			return x_topicManagerPrx != NULL;
		}

		bool XStormBase::InitTopicManager(const std::string& topicManagerDsb)
		{
			if(IsTopicManagerValid())
			{
				x_pLogger->error("Topic Manager is already initialized.");
				return false;
			}

			if(x_pIc->isShutdown())
			{
				x_pLogger->error("Shutdown is already called on Ice.Communicator.");
				return false;
			}

			try
			{
				Ice::ObjectPrx topicMngPrx = x_pIc->stringToProxy(topicManagerDsb);
				x_topicManagerPrx = IceStorm::TopicManagerPrx::checkedCast(topicMngPrx);
				if(x_topicManagerPrx == NULL)
				{
					x_pLogger->error("Proxy: " + topicManagerDsb + " is invalid");
					return false;
				}
				return true;
			}
			catch(const ::Ice::Exception& ex)
			{
				x_pLogger->error(ex.what());
			}
			return false;
		}

		IceStorm::TopicPrx XStormBase::RetrieveTopic(const std::string& topicName)
		{			
			if(!IsTopicManagerValid())
			{
				x_pLogger->error("Error: Topic Manager is not initialized.");
				return NULL;
			}

			if(x_pIc->isShutdown())
			{
				x_pLogger->error("Error: Shutdown is already called on Ice.Communicator.");
				return NULL;
			}

			IceStorm::TopicPrx topicPrx = NULL;
			try
			{
				topicPrx = x_topicManagerPrx->retrieve(topicName);
				return topicPrx;
			}
			catch(const ::IceStorm::NoSuchTopic&)
			{
				try
				{
					topicPrx = x_topicManagerPrx->create(topicName);
					return topicPrx;
				}
				catch(const ::IceStorm::TopicExists&)
				{
					x_pLogger->error(topicName + ": temporary error. try again.");					
				}
			}
			catch(const Ice::Exception& ex)
			{
				x_pLogger->error(ex.what());				
			}
			x_pLogger->error(" Can't retrive topic: " + topicName);	
			return NULL;
		}
	}
}


